package com.powerunion.datacollection.util;


import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import java.sql.DriverManager;
import javax.naming.InitialContext;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.config.ConfigUtil;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.model.SysServer;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.util.db.DBCommon;
import com.powerunion.util.log.LogHelper;

public class DBUtil extends DBCommon {
	private static final Logger logger = LogHelper.getInstance().getLogger(
			DBUtil.class);
    public DBUtil() {
        super();
    }

    public Connection getConnection() throws SQLException {
        String dsName = ConfigUtil.getInstance().getParameter("connection.datasource");
        try {
            if (dsName != null && !dsName.trim().equals("")) {
                String user = ConfigUtil.getInstance().getParameter("connection.username");
                String pwd = ConfigUtil.getInstance().getParameter("connection.password");
                InitialContext ctx = new InitialContext();
                if (user != null && !user.trim().equals(""))
                    return ((DataSource) ctx.lookup(dsName)).getConnection(user,pwd);
                else
                    return ((DataSource) ctx.lookup(dsName)).getConnection();
            } else {
                Class.forName(ConfigUtil.getInstance().getParameter("connection.driver_class"));
                return DriverManager.getConnection(
                        ConfigUtil.getInstance().getParameter("connection.url"),
                        ConfigUtil.getInstance().getParameter("connection.username"),
                        ConfigUtil.getInstance().getParameter("connection.password"));
            }
        } catch (Exception e) {
            throw new SQLException(
                    "DBUtil.getConnection: Exception connection db pool \n" +
                    e.getMessage());
        }
    }

    public String inDbEncode(String value) {
        return value;
    }

    public String outDbEncode(String value) {
        return value;
    }
    
	public Connection getTblConnection(SysServer server) throws DaoException {
		Connection conn = null;
		StringBuffer url = new StringBuffer();
		url.append("jdbc:oracle:thin:@").append(server.getDbmsSvr())
				.append(":").append(server.getPort()).append(":").append(
						server.getDbName());
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(url.toString(), server
					.getConnUser(), server.getConnPwd());
		}catch(Exception e){
			logger.error("", e);
			throw new DaoException("getMaintblConnection throw error!");
		}
		return conn;
	}
	
	/**
	 * 根据数据库字段的类型返回相应的sql.Types
	 * 
	 * @param fieldType
	 * @return
	 */
	public int getSqlTypes(String fieldType) {
		// 参数为空
		if (StringUtils.isEmpty(fieldType)) {
			String[] args = { "fieldType" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter fieldType NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		if (fieldType.toLowerCase().equals("number")) {
			return SqlType.BIGINT;
		} else if (fieldType.toLowerCase().equals("long")) {
			return SqlType.VARBINARY;
		} else if (fieldType.toLowerCase().equals("date")) {
			return SqlType.DATE;
		} else if (fieldType.toLowerCase().equals("varchar2")) {
			return SqlType.VARCHAR;
		} else if (fieldType.toLowerCase().equals("char")) {
			return SqlType.CHAR;
		} else if (fieldType.toLowerCase().equals("raw")) {
			return SqlType.VARBINARY;
		} else if (fieldType.toLowerCase().equals("timestamp")) {
			return SqlType.TIMESTAMP;
		} else if (fieldType.toLowerCase().equals("float")) {
			return SqlType.FLOAT;
		} else {
			return SqlType.VARCHAR;
		}

	}
	
	public String getSeq(Connection conn,String keyFld,String tableName) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql.append("select  max(to_number(").append(keyFld).append("))id from ").append(tableName);
		
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		int seq = -1;
		try{
			query.access();
		}catch(Exception e){
			logger.error("", e);
			throw new DaoException("getMaintblSeq throw error!");
		}
	
		if (query.resultSetAvailable()) {

			// 获取并处理记录集
			RsDataSet rs = new RsDataSet(query.getSqlResultSet());

			if (rs.rowCount > 0) {
				Integer key =  rs.getFieldValueAsInteger("id");
				if(key != null){
					seq = key.intValue()+1;
				}else {
					seq = 1;
				}
				
			}else {
				seq = 1;
			}

			rs.clearAll();
		}
		return String.valueOf(seq);
	}

}
